import React, { useEffect, useState } from "react";
import { Spin } from "antd";
import '../assets/index.css'
import { useChatStore,useUserStore } from '@/store'
import MessageList from '../components/messageList'
import CreateInput from '../components/createInput'
import AsideFunc from '../components/asideFunc'
import { getIDBase } from "@/utils";
import {chat} from '@/apis'
export default React.FC = () => {
  const [loading, setLoading] = useState(true)
  const {
    messageList,
    clearMessageListAction,
    clearCurrentConversationAction,
    createNewChatAction,
    currentConversation,
    chatHistoryList,
    addNewConversationAction,
    updateCurrentConversationAction,
    getConversationListFetchAction,
    getAllChatHistoryAction,
    deleteChatHistoryFetchAction
  } = useChatStore((state) => state)
  const { getUserInfoAction,userInfo } = useUserStore((state) => state)
  // 发送消息
  const onSendMessage = (data: any) => {
    if (currentConversation.id === undefined) {
      const newConversation = {
        id: 0,
        title: data.message,
        sendType: data.sendType,
        userId: userInfo.id,
        loading: true,
        createdAt: new Date().getTime(),
        updatedAt: new Date().getTime()
      }
      addNewConversationAction(newConversation)
      updateCurrentConversationAction(newConversation)
    }
    createNewChatAction(data)
  }
  useEffect(() => {

    setLoading(true)
    getUserInfoAction()
    setTimeout(async() => {
      // deleteChatHistoryFetchAction()
      clearMessageListAction()
      getConversationListFetchAction().then(() => {
        setLoading(false)
      })
    }, 500)
    return () => {
      clearCurrentConversationAction()
    }
  }, [])
  const onAnswerCreated = () => {
    console.log('onAnswerCreated')
  }
  // 点击某个对话记录
  const onClickConversationHandler = (conversation: any) => {
    if (currentConversation.id === conversation.id) {
      return
    }
    updateCurrentConversationAction(conversation)
    setLoading(true)
    getAllChatHistoryAction(conversation).then(() => {
      setLoading(false)
    })
  }
  return (
    <Spin spinning={loading} wrapperClassName="c_custom_spin_wrapper">
      <div className="c_contaienr">
        <AsideFunc onClickConversation={onClickConversationHandler}/>
        <div className="c_chat_wrapper">
          <MessageList messageList={messageList}/>
          <CreateInput onSendMessage={onSendMessage} />
        </div>
      </div>
    </Spin>
  );
};
